import Taro from '@tarojs/taro';
import { Camera, Button, View, Text, Image } from '@tarojs/components';
import { useState } from'react';
import './index.less'; // 引入样式文件

interface OCRResponse {
  statusCode: number;
  words_result: { words: string }[];
}

const OCRCameraComponent = () => {
  const [photoSrc, setPhotoSrc] = useState(null);
  const [recognizedText, setRecognizedText] = useState('');
  const [isLoading, setIsLoading] = useState(false);

  // 选择照片或调用相机
  const selectPhoto = () => {
    Taro.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res:any) => {
        setPhotoSrc(res.tempFilePaths[0]);
        // 将选择的照片转换为 Base64 编码
        Taro.getFileSystemManager().readFile({
          filePath: res.tempFilePaths[0],
          encoding: 'base64',
          success: (fileRes) => {
            const imageBase64 = fileRes.data;
            // 调用后端 API 进行 OCR 识别
            callOCR(imageBase64);
          },
        });
      },
    });
  };

  // 调用后端 API 进行 OCR 识别
  const callOCR = (imageBase64) => {
    setIsLoading(true);
    Taro.request<OCRResponse>({
      url: 'http://localhost:3000/ocr',
      method: 'POST',
      data: { image: imageBase64 },
      header: {
        'Content-Type': 'application/json',
      },
    }).then(response => {
      setIsLoading(false);
      if (response.statusCode === 200 && response.data.words_result) {
        setRecognizedText(response.data.words_result.map(item => item.words).join('\n'));
      } else if (response.statusCode === 400) {
        Taro.showToast({
          title: '请求参数错误',
          icon: 'none',
        });
      } else if (response.statusCode === 500) {
        Taro.showToast({
          title: '服务器内部错误',
          icon: 'none',
        });
      } else {
        Taro.showToast({
          title: 'OCR 识别失败，未知错误',
          icon: 'none',
        });
      }
    }).catch(error => {
      setIsLoading(false);
      console.error('OCR 识别错误:', error);
      Taro.showToast({
        title: '网络请求失败，请检查网络',
        icon: 'none',
      });
    });
  };

  return (
    <View className='ocr-camera-component'>
      <Button className='select-photo-btn' onClick={selectPhoto}>选择照片</Button>
      {photoSrc && <Image src={photoSrc} className='photo' />}
      {isLoading && <Text>正在识别中...</Text>}
      {recognizedText && <Text>{recognizedText}</Text>}
    </View>
  );
};

export default OCRCameraComponent;